// request.ts
import globalConfig from '@/js/globals';
interface RequestOptions {
  url: string;
  data?: any;
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
  header?: Record<string, any>;
  timeout?: number; // 设置请求超时时间，单位为毫秒
}

interface ResponseData<T> {
  code: number;
  message: string;
  data: T;
}

class Request {
  private baseUrl: string = ''; // 默认基础 URL
  private defaultTimeout: number = 30000; // 默认超时时间，单位为毫秒
  private token: string = ''; // 保存 Token

  constructor(baseUrl: string) {
    this.baseUrl = baseUrl;
  }

  // 设置Token
  setToken(token: string) {
    this.token = token;
  }

  // GET 请求
  get<T>(url: string, data?: any, header?: Record<string, any>): Promise<ResponseData<T>> {
    return this.request<T>({ url, data, method: 'GET', header });
  }

  // POST 请求 (application/json)
  postJson<T>(url: string, data?: any, header?: Record<string, any>): Promise<ResponseData<T>> {
    const defaultHeader = {
      'Content-Type': 'application/json'
    };
    return this.request<T>({ url, data, method: 'POST', header: { ...defaultHeader, ...(header || {}) } });
  }

  // POST 请求 (multipart/form-data)
  postFormData<T>(url: string, data?: Record<string, any>, header?: Record<string, any>): Promise<ResponseData<T>> {
    const formData = this.convertToFormData(data);
    const defaultHeader = {
      'Content-Type': 'multipart/form-data'
    };
    return this.request<T>({ url, data: formData, method: 'POST', header: { ...defaultHeader, ...(header || {}) } });
  }

  // 统一的请求处理
  private request<T>(options: RequestOptions): Promise<ResponseData<T>> {
    return new Promise((resolve, reject) => {
      // 请求之前拦截：比如可以统一处理 token
      const headers = {
        ...(options.header || {})
      };
      if (this.token) {
        headers['Authorization'] = `Bearer ${this.token}`;
      }

      const controller = new AbortController();
      const timeoutId = setTimeout(() => controller.abort(), options.timeout || this.defaultTimeout);

      fetch(this.baseUrl + options.url, {
        method: options.method || 'GET',
        headers: headers,
        body: options.method !== 'GET' ? JSON.stringify(options.data) : undefined,
        signal: controller.signal
      })
      .then(async response => {
        clearTimeout(timeoutId);
        const data: ResponseData<T> = await response.json();
        if (data.code === 200) {
          resolve(data);
        } else {
          // 使用原生alert替代uni.showToast
          alert(data.message || '请求错误');
          reject(data);
        }
      })
      .catch(error => {
        clearTimeout(timeoutId);
        // 使用原生alert替代uni.showToast
        alert('网络请求失败');
        reject(error);
      });
    });
  }

  // 将对象转换为FormData格式
  private convertToFormData(data?: Record<string, any>): FormData {
    const formData = new FormData();
    if (data) {
      Object.keys(data).forEach((key) => {
        formData.append(key, data[key]);
      });
    }
    return formData;
  }
}

export default new Request(globalConfig.apiBaseUrl); // 将基础 URL 改为你的 API 地址
